#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from robyn import SubRouter, Request
from robyn.exceptions import HTTPException
from robyn import Response, jsonify
from sqlmodel import Session, select
from sqlmodel.ext.asyncio.session import AsyncSession
import logging
import time

from common.result import JsonResult
from common.exception.exception_handlers import default_exception_handler
from settings.config import settings
from database.db import async_engine, sync_engine
from app.admin.model.user import User
from app.admin.service.user import user_service

router = SubRouter(__file__, prefix=f'{settings.ROBYN_API_V1_PATH}/test')
router.exception(default_exception_handler)

logger = logging.getLogger(__name__)

@router.get("/dict")
def testd(reqest: Request):
    time.sleep(1000 * 600)
    return JsonResult.success()

@router.get("/dict2")
def testd2(reqest: Request):
    return JsonResult.success()

@router.get("/response")
async def teste():
    return Response(
        status_code=200,
        description=jsonify({}),
        headers={"Content-Type": "application/json"}
    )
    
@router.get("/exception")
async def teste():
    raise HTTPException(status_code=500, detail="测试 HTTPException")

@router.get("/users")
def testsu():
    with Session(sync_engine) as session:
        query = (
            select(User)
            .offset(0)
            .limit(10)
            .order_by('id')
        )
        users = session.exec(query).all()
        data = []
        for u in users:
            data.append(u.model_dump())
        return JsonResult.success(data=data)

@router.get("/user")
async def testu(request: Request):
    users = await user_service.page()
    data = []
    for u in users:
        data.append(u.model_dump())
    return JsonResult.success(data=data)